package org.paradigmshift.timelapse.ui
import scala.swing.event.EditDone
import scala.swing.BorderPanel
import scala.swing.BoxPanel
import scala.swing.Orientation
import scala.swing.ProgressBar
import scala.swing.Swing
import scala.swing.TextField
import org.paradigmshift.timelapse.TimeLapsePreferences
import org.paradigmshift.timelapse.daos.IssueDao
import org.paradigmshift.timelapse.TimeLapsePreferences
import javax.swing.JOptionPane
import org.paradigmshift.timelapse.domain.Issue
import scala.swing.Action
import scala.swing.CheckBox

class SearchPanel extends BorderPanel {
  
  def defaultSearchList():List[Issue] = {
    val defaultSearch = TimeLapsePreferences.getDefaultSearch
    if ( defaultSearch != "" ) IssueDao.findByFullText( defaultSearch )
    else {
      val user = TimeLapsePreferences.getUsername
      if ( user != "" ) {
        val param = "assignee=" + user + " AND resolution=unresolved"
        IssueDao.findByJson( Map[String,Any] ( "jql" -> param ) )
      }
      else Nil
    }
  }
    
  // Inputs and visual cues
  val issueModel = new IssueTableModel
  issueModel.setIssues( defaultSearchList )
  
  val searchBox = new TextField( 15 ) {
    action = Action( "search" ) {
      val keyPattern = "(\\w+-\\d+)".r
      val results:List[Issue] = try {
        if ( !TimeLapsePreferences.getUseJql ) {
          text match {
            case keyPattern( text ) => List( IssueDao.findByKey( text ).get )
            case "" => defaultSearchList
            case text => IssueDao.findByFullText( text )
          }
        }
        else {
          IssueDao.findByJson( Map[String,Any] ( "jql" -> text ) )
        }
      }
      catch {
        case e: Exception => {
          JOptionPane.showMessageDialog( this.peer, "Failed to connect to JIRA.  Check your connection preferences." )
          Nil
        }
      }
      
      issueModel.setIssues( results )
    }
  }
  
  val table = new TimeLapseTable( issueModel )
  var scrollPane = new TimeLapseTableScrollPane( table )
  
  // Layout
  val searchControls = new BoxPanel( Orientation.Horizontal ) {
    contents += new CheckBox
    contents += searchBox
  }
  val topPanel = new BorderPanel() { layout( searchBox ) = BorderPanel.Position.East }
  topPanel.border = Swing.EmptyBorder( 5, 5, 5, 5 )
  
  val centerPanel = new BoxPanel( Orientation.Horizontal )
  centerPanel.contents += scrollPane
  
  layout( topPanel ) = BorderPanel.Position.North
  layout( centerPanel ) = BorderPanel.Position.Center
  
  val columnModel = table.peer.getColumnModel()
  val lastColumn = columnModel.getColumn( columnModel.getColumnCount() - 1 )
  lastColumn.setPreferredWidth( 500 )
    
  // LAF
  if ( OSValidator.isMac ) {
    searchBox.peer.putClientProperty( "JTextField.variant", "search" )
  }
}